package com.example.jedis.client.transport;

import code.example.tool.LogFactory;
import redis.clients.jedis.exceptions.JedisException;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class RedisTransportForLog implements RedisTransport{
    RedisTransport redisTransport = null;

   public RedisTransportForLog(RedisTransport redisTransport){
       this.redisTransport = redisTransport;
   }

    @Override
    public ByteBuffer read() {

        ByteBuffer byteBuffer =  redisTransport.read();
        byteBuffer.flip();
        byte [] data = new byte [byteBuffer.remaining()];
        byteBuffer.get(data);
        LogFactory.getLog().info("read :["+dataToString(data)+"]");
        return byteBuffer;
    }

    public int  write(ByteBuffer byteBuffer){
        byteBuffer.mark();
        byte [] data = new byte [byteBuffer.remaining()];
        byteBuffer.get(data);
        LogFactory.getLog().info("write :["+dataToString(data)+"]");
        byteBuffer.reset();
        return redisTransport.write(byteBuffer);
    }

    private String dataToString( byte [] data ){
       StringBuilder sb = new StringBuilder();
       for(int i=0;i<data.length;i++){
           char c = (char)data[i];
           if(c == '\r'){
               sb.append("\\r");
           }else if(c == '\n'){
               sb.append("\\n");
           }else {
               sb.append(c);
           }
       }
        return sb.toString();
    }
    public int  read(ByteBuffer byteBuffer) {
        int size = redisTransport.read(byteBuffer);
        return size;
    }


}
